package com.qf.blog.web.controller;

import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.service.IInvitataionService;
import com.qf.blog.web.service.IUserService;
import com.qf.blog.web.vo.IndexDataVo;
import com.qf.blog.web.vo.MyPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/indexController")
public class IndexController {

    @Autowired
    private IInvitataionService invitataionService;

    @Value("${blog.autoLogin}")
    private Boolean autoLogin;

    @Autowired
    private IUserService userService;


    @GetMapping("/index")
    public String index(MyPage<IndexDataVo> page, Integer order, ModelMap map) throws Exception {

        if (autoLogin) {
            // 试下自动登录
            autuLogin();
        }

        if (order == null) {
            order = 1;
        }

        // 1.获取数据
//        List<IndexDataVo> list = invitataionService.indexDataList(order);
        invitataionService.indexDataPage(page, order);

        // 2.放到Map中
        page.setPath("/indexController/index");// 用户点击下一页的时候应该请求那个接口？
        map.put("page", page);

        // 3.跳转到视图
        return "view/index";
    }

    public void autuLogin() {
        // 用admin账号登录
        UserEntity userEntity = userService.getById(102);
        userEntity.setPassword(null);

        // 还有一种方式可以得到HttpSession
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        request.getSession().setAttribute("loginUser", userEntity);
    }
}
